<?php
namespace app\tcms\validate;
use think\Db;
class User extends FrontendBase
{
    // 验证规则
    protected $rule = [
        'username'              => 'require',
        'password'              => 'require|length:6,18',       // 密码长度6-18位
        'confirm_password'      => 'require|confirm:password',

        'code'                  => 'require|checkCode',
        'nickname'              => 'require',
        'city_id'               => 'require|regex:\d{1,}',
        'gender'                => 'require',
        'signature'             => 'require',
        'oldpassword'           => 'require|checkOldpassword'
    ];


    // 应用场景
    protected $scene = [
        'login'             =>  ['username',"password"],
        'check_register'      =>  ['username'=>'require|email|unique:User'],
        'register'      =>  ['username'=>'require|length:3,12|unique:User','password','confirm_password'],
        'updateBaseInfo'    => ['nickname','city_id','gender','signature'],
        'resetpass'     =>  ['oldpassword','password'=>'require|length:6,18|different:oldpassword','confirm_password'=>'require|confirm:password'],
        'check_forget'  => ['username'=>'require|checkUsername'],
        'forget'        =>  ['username'=>'require|checkUsername','password','confirm_password','code','verify'],

    ];
    protected $message  =   [
        'username.require'              => '用户名必须',
        'username.unique'               => '用户名已经存在',
        'username.length'               => '用户名长度3至12位',
        'password.require'              => '密码必须',
        'password.different'            => '新密码与原密码不能相同',
        'confirm_password.require'      => '请再次输入密码',
        'confirm_password.confirm'      => '两次新密码不一致'
    ];
    /*
        检查老密码是否正确
    */
    protected function checkOldpassword($value){
        $user_id=session("frontend_author_sign")['userid'];
        if(Db::name("User")->where(['id'=>$user_id,'password'=>'###'.md5($value.DATA_ENCRYPT_KEY)])->count()==0){
            return "原密码不正确";
        }
        return true;
    }
    /*
        验证code
    */
    protected function checkCode($value){
        $username=input("username");
        $map['receiver']=$username;
        $map['code']=$value;
        $map['type']="mail";
        $map['status']=1;
        $map['session_id']=session("user_session_id");
        $listPushLog=Db::name('PushLog')->where($map)->order("add_time DESC")->find();
        if($listPushLog){
            if(time()-$listPushLog['add_time']>7200){
                return "邮箱验证码已失效，请重新发送";
            }else{
                return true;
            } 
        }else{
            return "邮箱验证码错误";
        }
    }

    /*
        查询邮箱是否已经存在 
    */
    protected function checkUsername($value){
        $listUser=Db::name('User')->where("username='$value'")->find();
        if(count($listUser)==0){
            return "该用户不存在";
        }
        return true;
    }
}